#include "junix.h"
using namespace std;

void jreplace(string& s,const string& f,const string& t)
{
	string::size_type beg=0,pos=0;
	while(true)
	{
		if( (pos=s.find(f,beg)) == string::npos)
			break;
		else 
		{
			s.replace(pos, f.size(), t);
			beg = pos + t.size();
		}
	}
}

string basename(const string & path)
{
	string::size_type pos = path.rfind("/");
	if(pos ==string::npos)
		return string(path);
	else
		return string(path,pos+1);
}

void remove_tag(string& s)
{
	static string tags[]=
	{
		"<b>","</b>",
		"<tt>","</tt>",
		"<p>","</p>",
		"<br>"
	};

	string::size_type pos;
	for(size_t i=0;i<sizeof(tags)/sizeof(tags[0]);i++)
	{
		pos=s.find(tags[i]);
		if(pos == string::npos)
			continue;
		else 
		{
			s.erase(pos,tags[i].size());
		}
	}

	string::size_type tbeg,tend;
	while(true)
	{
		tbeg=s.find("<");
		tend=s.find(">");
		if( tbeg!=string::npos && 
			tend != string::npos &&
			tend > tbeg)
		{
			s.erase(tbeg, tend-tbeg+1);
		}
		else if( tbeg!=string::npos && 
			     tend != string::npos &&
				 tbeg > tend)
		{
			s.erase(0,tend+1);
		}
		else if( tbeg != string::npos &&
				tend==string::npos )
		{
			s.erase(tbeg);
		}
		else if( tbeg == string::npos &&
				tend != string::npos )
		{
			s.erase(0,tend+1);
		}
		else
		{
			break;
		}
	}
	

	jreplace(s,"&lt;","<");
	jreplace(s,"&gt;",">");
	jreplace(s,"&amp;","&");

}

void trim(string& s)
{
	while( !s.empty() && !isgraph(s[0]) )
		s.erase(0,1);

	while(!s.empty() && !isgraph(s[s.size()-1]))
		s.erase(s.size()-1);
}

int main(int argc, char **argv)
{
	if(argc != 2)
	{
		cout<<"Usage:"<<argv[0]<<" html_file"<<endl;
		exit(1);
	}

	string output_file_name=basename( string(argv[1]) )+".txt";
	ifstream html_file(argv[1]);
	ofstream txt_file(output_file_name.data());
	string line;

	while(getline(html_file,line))
	{
		remove_tag(line);
		trim(line);
		if(!line.empty())
			txt_file<<line<<endl;
	}

	html_file.close();
	txt_file.close();

}
